<template>
  <div class="resource-upload">
    <nav-header>
      <template slot="menuBefore">
        <li>
          <router-link to="/resources/resource/teaching-resources" tag="a"
            >教学资源</router-link
          >
        </li>
        <li class="gap">&gt;</li>
      </template>
    </nav-header>

    <div
      class="u_resource"
      v-loading="loading.status"
      :element-loading-text="loading.txt"
    >
      <el-form
        :model="dataForm"
        :rules="rules"
        ref="dataForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="上传资源" prop="select_or_not">
          <div class="r_fileBox">
            <uploader
              :options="uploadOptions"
              :autoStart="false"
              ref="uploader"
              :file-status-text="statusText"
              @file-added="fileAdd"
              @file-removed="fileRemoved"
              @file-success="fileSuccess"
              @file-error="fileFail"
              class="uploader-example"
            >
              <uploader-unsupport></uploader-unsupport>
              <uploader-btn
                :directory="false"
                :attrs="attrs"
                v-if="selectFileShow"
                :single="true"
                >选择资源</uploader-btn
              >
              <uploader-list></uploader-list>
            </uploader>
          </div>
          <el-input v-model="dataForm.select_or_not" v-show="0"></el-input>
        </el-form-item>
        <el-form-item label="资源名称" prop="name">
          <el-input
            v-model="dataForm.name"
            maxlength="20"
            placeholder="20个字符内"
          ></el-input>
        </el-form-item>
        <div class="r_typeClass">
          <template v-if="!$store.state.platformInformation">
            <el-form-item
              label="学段"
              prop="study_section_id"
            >
              <el-select
                v-model="dataForm.study_section_id"
                filterable
                @change="relateChange($event, 'study_section')"
                placeholder="请选择学段"
              >
                <el-option
                  v-for="item in orgLevel2"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="年级"
              prop="grade_id"
            >
              <el-select
                v-model="dataForm.grade_id"
                filterable
                @change="relateChange($event, 'grade')"
                placeholder="请选择年级"
              >
                <el-option
                  v-for="item in orgLevel3"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="科目"
              prop="subject_id"
            >
              <el-select
                v-model="dataForm.subject_id"
                @change="relateChange($event, 'subject')"
                filterable
                placeholder="请选择科目"
              >
                <el-option
                  v-for="item in orgSubject"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="版本"
              prop="version_id"
            >
              <el-select
                v-model="dataForm.version_id"
                @change="relateChange($event, 'version')"
                filterable
                placeholder="选择版本"
              >
                <el-option
                  v-for="item in orgVersion"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="教材"
              prop="material_id"
            >
              <el-select
                v-model="dataForm.material_id"
                @change="relateChange($event, 'material')"
                filterable
                placeholder="选择教材"
              >
                <el-option
                  v-for="item in orgMaterial"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="章"
              prop="list_1_id"
            >
              <el-select
                v-model="dataForm.list_1_id"
                @change="relateChange($event, 'list_1')"
                filterable
                placeholder="选择章"
              >
                <el-option
                  v-for="item in orgList1"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              label="节"
              prop="list_2_id"
            >
              <el-select
                v-model="dataForm.list_2_id"
                filterable
                placeholder="选择节"
              >
                <el-option
                  v-for="item in orgList2"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </template>
          <el-form-item
            v-if="$store.state.checkLevel"
            label="类别"
            style="width: 220px"
            prop="catename"
          >
            <el-select
              v-model="dataForm.cate_id"
              @change="getVal"
              filterable
              placeholder="选择分类"
            >
              <el-option
                v-for="item of resoureKindData"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-button
            v-if="$store.state.checkLevel"
            style="margin-left: 10px"
            type="text"
            @click="addReskindTrigger()"
            >添加类别</el-button
          >
        </div>
        <el-form-item
          v-if="!$store.state.checkLevel"
          label="简介"
          prop="profile"
        >
          <el-input
            type="textarea"
            :rows="2"
            placeholder="不超200字"
            maxlength="200"
            v-model="dataForm.profile"
          ></el-input>
        </el-form-item>
        <el-form-item label="权限" prop="authority">
          <el-radio-group v-model="dataForm.authority">
            <el-radio :label="1">公开</el-radio>
            <el-radio :label="0">私有</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="允许下载" prop="is_download">
          <el-radio-group v-model="dataForm.is_download">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item class="r_submitBox">
          <el-button @click="cancel()">取消</el-button>
          <el-button type="primary" @click="submitForm('dataForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <!-- 添加分类----------------------------------------------------- -->
    <el-dialog
      title="资源类别"
      :visible.sync="addReskindFlag"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleClosed()"
      width="30%"
    >
      <p>
        添加类别：
        <el-input
          type="text"
          style="width: 60%"
          placeholder="输入资源分类，不超过8个字"
          @keyup.enter.native="addCategory"
          v-model.trim="addKindvalue"
          maxlength="8"
        >
        </el-input>
        <el-button type="primary" @click="addCategory">添加</el-button>
      </p>
      <p style="padding-bottom: 30px">
        分类管理：<br />
        <el-tag
          size="mini"
          v-for="item in resoureKindData"
          :key="item.id"
          @close.stop="delCategory(item.id)"
          style="margin-top: 5px; margin-right: 5px"
          closable
          >{{ item.name }}
        </el-tag>
      </p>
    </el-dialog>
    <!-- 添加分类-------------------------------------------------------------------- -->
  </div>
</template>

<script>
import { uploaderFileFail } from "./../../../tools/tool";

export default {
  data() {
    return {
      resoureKindData: [],
      addReskindFlag: false, //添加类别弹窗状态
      addKindvalue: "",
      loading: {
        status: false,
        txt: "获取数据...",
      },
      orgLevel2: [],
      orgLevel3: [],
      orgSubject: [],
      orgVersion: [],
      orgMaterial: [],
      orgList1: [],
      orgList2: [],
      orgLevel2Param: {
        //获取学段参数
        level: 2,
        pid: null,
        direction: "balance",
      },
      orgLevel3Param: {
        //获取年纪参数
        level: 3,
        pid: null,
        direction: "balance",
      },
      subjectParam: {
        //获取科目,版本，参数
        type: 2,
        org_id: null,
        status: 1,
      },
      versionParam: {
        //获取科目,版本，参数
        type: 2,
        org_id: null,
        sub_id: null,
        status: 1,
      },
      materialParam: {
        //获取科目,版本，参数
        org_id: null,
        sub_id: null,
        ver_id: null,
        status: 1,
      },
      listParam1: {
        pid: 0,
        material_id: null,
        level: 1,
      },
      listParam2: {
        pid: 0,
        material_id: null,
        level: 2,
      },
      selectFileShow: true, //是否显示选择文件按钮
      uploadOptions: {
        target: this.BASE_URL + "/api/resource/res_upload",
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
      },
      selectFileOrNot: false, //是否选中文件
      uploadOrNot: false, //是否已经上传
      attrs: {
        //accept: ['image/*','video/*','audio/*','document/doc', 'document/txt', 'document/docx','document/csv', 'document/xls','document/xlsx', 'document/ppt', 'document/pptx']
      },
      statusText: {
        success: "上传成功",
        error: "上传出错",
        uploading: "正在上传...",
        paused: "暂停",
        waiting: "等待上传",
      },
      uploadInfo: {
        file_name: "",
        file_path: "",
        file_size: 0,
      },
      dataForm: {
        name: "", //资源名称
        study_section_id: null, //学段
        grade_id: null, //年级
        subject_id: null, //科目
        version_id: null, //版本
        material_id: null, //教材
        list_1_id: null, // 章id
        list_2_id: null, // 节id
        cate_id: "", // 类别id
        authority: 1, //权限
        is_download: 1, //允许下载
        profile: "",
        format_pdf: 0,
        select_or_not: "",
      },
      rules: {
        select_or_not: [
          { required: true, message: "请选择上传的文件", trigger: "blur" },
        ],
        catename: [{ message: "请输入资源类别名称", trigger: "blur" }],
        name: [
          { required: true, message: "请输入资源名称", trigger: "blur" },
          {
            pattern: this.rules.spaceKey.reg,
            message: this.rules.spaceKey.msg,
            trigger: "blur",
          },
          { min: 1, max: 50, message: "长度在 1 到 50 个字符" },
        ],
        desc: [{ min: 1, max: 200, message: "长度在 1 到 200 个字符" }],
        study_section_id: [
          { required: true, message: "请选择学段", trigger: "change" },
        ],
        grade_id: [
          { required: true, message: "请选择年级", trigger: "change" },
        ],
        subject_id: [
          { required: true, message: "请选择科目", trigger: "change" },
        ],
        version_id: [
          { required: false, message: "请选择版本", trigger: "change" },
        ],
        material_id: [
          { required: false, message: "请选择教材", trigger: "change" },
        ],
        list_1_id: [
          { required: false, message: "请选择章", trigger: "change" },
        ],
        list_2_id: [
          { required: false, message: "请选择节", trigger: "change" },
        ],
      },
      uploadRetryTimes: 100, //文件最大重传次数
    };
  },
  created() {
    this.getDisk();
    this.getOrgLevel2();
    this.getSourceKind();
  },
  methods: {
    // 添加类别------------------------------------
    addReskindTrigger() {
      // 弹窗状态
      this.addReskindFlag = true;
    },
    // 添加类别------------------------------------
    /**获取资源类别 */
    getSourceKind() {
      let success = (res) => {
        this.resoureKindData = res.data;
        this.resoureKindData.unshift({ id: 0, name: "全部" });
        console.log(res.data, 333);
      };
      this.$ajax.get("api/resource/resource_cate", { func: { success } });
    },
    handleClosed() {
      this.addKindvalue = "";
    },
    /**添加资源类别 */
    addCategory() {
      if (this.addKindvalue == "") {
        this.$message.error("内容不能为空");
        return;
      }
      if (
        this.resoureKindData.some((i) => {
          return i.name == this.addKindvalue;
        })
      ) {
        this.$message.error("已有该类别");
        return;
      }

      let params = {
        name: this.addKindvalue,
      };
      let success = (res) => {
        this.$message.success(res.msg);
        this.addKindvalue = "";
        this.getSourceKind();
      };
      let fail = (data) => {
        this.$message.error(data.msg);
        this.addKindvalue = "";
      };
      this.$ajax.post("api/resource/resource_cate", params, {
        func: { success, fail },
      });
    },
    /**删除资源类别--- */
    delCategory(id) {
      let params = {
        id: id,
      };
      let success = (res) => {
        this.$message.success(res.msg);
        this.getSourceKind();
      };
      this.$ajax.delete("api/resource/resource_cate", {
        params,
        func: { success },
      });
    },
    getVal(val) {
      // 获取当前选中项，
      console.log(val, 888);
      this.dataForm.cate_id = val; // 把获取到的分类id 给 添加视频的视频分类id字段
    },
    /**
     * 获取系统存储容量
     */
    getDisk() {
      this.loading.status = true;

      let success = (res) => {
        if (res.data[17] === 0) {
          this.loading.status = false;
        } else {
          this.$message.error(
            "系统存储容量小于5G，请清理存储空间（视频/资源文件）或升级存储"
          );
          this.$router.push("/resources/resource/teaching-resources");
        }
      };

      this.$ajax.get("api/system/system_info", { func: { success: success } });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.selectFileOrNot) {
            this.fileUpload();
          } else {
            this.resourceSave();
          }
        } else {
          return false;
        }
      });
    },
    resourceSave() {
      let resourceParam = deep_clone(this.dataForm);
      if (this.uploadOrNot) {
        resourceParam.path = this.uploadInfo.file_path;
        resourceParam.filesize = this.uploadInfo.file_size;
        resourceParam.postfix = this.uploadInfo.post_fix;
      }
      let success = (data) => {
        this.$router.push("/resources/resource/teaching-resources");
        this.$message.success(data.msg);
      };
      //执行请求，并将回调方法变成config成员以便鉴权过期可以执行
      if (!is_empty(resourceParam.id) && parseInt(resourceParam.id) > 0) {
        this.$ajax.put("api/resource/vue_resource", resourceParam, {
          func: { success: success },
        });
      } else {
        this.$ajax.post("api/resource/vue_resource", resourceParam, {
          func: { success: success },
        });
      }
    },
    cancel() {
      this.$router.go(-1);
    },
    //上传成功的事件
    fileSuccess(rootFile, file, message, chunk) {
      Uploader.cancel();
      var mess = eval("(" + message + ")");
      mess = handleResponseData(mess);

      if (parseInt(mess.data.status) === 1) {
        this.uploadOrNot = true;
        this.uploadInfo.file_name = mess.data.file_name;
        this.uploadInfo.file_path = mess.data.file_path;
        this.uploadInfo.post_fix = mess.data.post_fix;
        this.resourceSave();
      }
    },
    fileFail(rootFile, file, message, chunk) {
      Uploader.cancel();

      uploaderFileFail(this, Uploader, file, message);
    },
    fileAdd(file, fileList) {
      if (file.size > 2000 * 1024 * 1024) {
        this.$message.error("附件大小不能超过2G");
        file.ignored = true;
        return false;
      }
      this.uploadInfo.file_size = file.size;
      this.selectFileOrNot = true;
      this.selectFileShow = false;
      this.dataForm.select_or_not = "true";
    },
    fileRemoved(file) {
      this.selectFileOrNot = false;
      this.selectFileShow = true;
      this.dataForm.select_or_not = "";
    },
    fileUpload() {
      Uploader.upload();
    },
    //获取学段
    getOrgLevel2() {
      let success = (data) => {
        this.orgLevel2 = data.data;
      };
      if (this.$store.state.checkLevel) {
        this.$ajax.get("api/newlevel/platform_org", {
          params: this.orgLevel2Param,
          func: { success: success },
        });
      } else {
        this.$ajax.get("api/org/org", {
          params: this.orgLevel2Param,
          func: { success: success },
        });
      }
    },
    //获取年级
    getOrgLevel3() {
      let success = (data) => {
        this.orgLevel3 = data.data;
      };
      if (this.$store.state.checkLevel) {
        this.$ajax.get("api/newlevel/platform_org", {
          params: this.orgLevel3Param,
          func: { success: success },
        });
      } else {
        this.$ajax.get("api/org/org", {
          params: this.orgLevel3Param,
          func: { success: success },
        });
      }
    },
    //获取科目
    getSubject() {
      let success = (data) => {
        this.orgSubject = data.data;
      };
      if (this.$store.state.checkLevel) {
        this.$ajax.get("api/newlevel/platform_subject", {
          params: this.subjectParam,
          func: { success: success },
        });
      } else {
        this.$ajax.get("api/cate/subject", {
          params: this.subjectParam,
          func: { success: success },
        });
      }
    },
    //获取版本
    getVersion() {
      let success = (data) => {
        this.orgVersion = data.data;
      };
      this.$ajax.get("api/cate/version", {
        params: this.versionParam,
        func: { success: success },
      });
    },
    //获取教材
    getMaterial() {
      let success = (data) => {
        this.orgMaterial = data.data;
      };
      this.$ajax.get("api/cate/material", {
        params: this.materialParam,
        func: { success: success },
      });
    },
    //获取章
    getList1() {
      let success = (data) => {
        this.orgList1 = data.data;
      };
      this.$ajax.get("api/cate/cate_list", {
        params: this.listParam1,
        func: { success: success },
      });
    },
    //获取节
    getList2() {
      let success = (data) => {
        this.orgList2 = data.data;
      };
      this.$ajax.get("api/cate/cate_list", {
        params: this.listParam2,
        func: { success: success },
      });
    },

    resetOrgGrade() {
      this.dataForm.grade_id = 0;
    },
    relateChange(newVal, type) {
      switch (type) {
        case "study_section":
          this.dataForm.grade_id = null;
          this.dataForm.subject_id = null;
          this.dataForm.version_id = null;
          this.dataForm.material_id = null;
          this.dataForm.list_1_id = null;
          this.dataForm.list_2_id = null;

          this.orgLevel3 = [];
          this.orgSubject = [];
          this.orgVersion = [];
          this.orgMaterial = [];
          this.orgList1 = [];
          this.orgList2 = [];

          this.orgLevel3Param.pid = newVal;
          this.getOrgLevel3();
          break;
        case "grade":
          this.dataForm.subject_id = null;
          this.dataForm.version_id = null;
          this.dataForm.material_id = null;
          this.dataForm.list_1_id = null;
          this.dataForm.list_2_id = null;

          this.orgSubject = [];
          this.orgVersion = [];
          this.orgMaterial = [];
          this.orgList1 = [];
          this.orgList2 = [];

          this.subjectParam.org_id = newVal;
          this.getSubject();

          this.versionParam.org_id = newVal;

          this.materialParam.org_id = newVal;
          break;
        case "subject":
          this.dataForm.version_id = null;
          this.dataForm.material_id = null;
          this.dataForm.list_1_id = null;
          this.dataForm.list_2_id = null;

          this.orgVersion = [];
          this.orgMaterial = [];
          this.orgList1 = [];
          this.orgList2 = [];

          this.versionParam.sub_id = newVal;
          this.getVersion();

          this.materialParam.sub_id = newVal;
          break;
        case "version":
          this.dataForm.material_id = null;
          this.dataForm.list_1_id = null;
          this.dataForm.list_2_id = null;

          this.orgMaterial = [];
          this.orgList1 = [];
          this.orgList2 = [];

          this.materialParam.ver_id = newVal;
          this.getMaterial();
          break;
        case "material":
          this.dataForm.list_1_id = null;
          this.dataForm.list_2_id = null;

          this.orgList1 = [];
          this.orgList2 = [];

          this.listParam1.material_id = newVal;
          this.listParam2.material_id = newVal;
          this.getList1();
          break;
        case "list_1":
          this.dataForm.list_2_id = null;

          this.orgList2 = [];

          this.listParam2.pid = newVal;
          this.getList2();
          break;
        default:
          break;
      }
    },
  },
  components: {
    // uploader
  },

  mounted() {
    // 获取uploader对象
    this.$nextTick(() => {
      window.Uploader = this.$refs.uploader.uploader;
    });
  },
};
</script>

<style lang="scss">
.resource-upload {
  .el-form {
    max-width: 800px;
    margin-top: 30px;
  }
  /*.uploader-btn{
 		color: #fff;
 		background-color: #409EFF;
 		border-color: #409EFF;
 		font-size: 12px;
 	}*/
  .r_typeClass {
    > div {
      display: inline-block;
      vertical-align: top;
      width: 303px;
    }
  }

  .r_fileBox {
    width: 100%;
  }
  .uploader-file-name {
    width: 30%;
  }
  .uploader-file-meta {
    width: 2% !important;
  }

  .uploader-file-status {
    width: 40% !important;
  }
}
</style>